#include <stdio.h>
#include <string.h>
#include "proc.h"
#include "parse.h"

/**
 * Returns the index of the root node (init)
 */
int find_root()
{
	int i;
	for (i = 0; i < size; i++) {
		if (proc_tree[i].pid == 1)
			return i;
	}

}

int get_size()
{
	return size;
}

void build_index()
{
	size = parse_ps();
}

/**
 * Returns the index of a node given its pid
 * (-1 for roots eg init)
 */
int find_index(int pid) {
	int me = size - 1;
	for(; me >= 0; me--) {
		if (proc_tree[me].pid == pid)
			break;
	}

	return me;
}

/**
 * Add child under the parent
 * @param parent the parent index
 * @param child the child index
 */
void add_child(int parent, int child)
{
	// Is it the the first birth?
	if (proc_tree[parent].child == -1) {
		proc_tree[parent].child = child;
	} else { // Add as last sibling
		int sibling = proc_tree[parent].child;
		while (proc_tree[sibling].sibling != -1) {
			sibling = proc_tree[sibling].sibling;
		}

		proc_tree[sibling].sibling = child;
	}
}

void build_tree()
{
	int i=0;
	for (;i < size; i++) {
		int parent = find_index(proc_tree[i].ppid);
		// Set child's parent field 
		proc_tree[i].parent = parent;
		// If i am not a root (eg init) add me as a child under my parent
		if (parent != -1)
			add_child(parent, i);
	}
}

void mark_level()
{
	
	int i;
	for (i = 0; i < size; i++) {
		int level = 0;
		int parent = proc_tree[i].parent;
		while (parent != -1) {
			level++;
			parent = proc_tree[parent].parent;
		}
		proc_tree[i].level = level;
	}
}

void print_tree(int root)
{
	printf ("%*s" "%d %d %s\n", proc_tree[root].level,"", 
		proc_tree[root].pid, proc_tree[root].ppid, proc_tree[root].name);
	
	int child = proc_tree[root].child;
	if(child  != -1) {
		print_tree(child);
	}

	int sibling = proc_tree[root].sibling;
	if (sibling != -1) {
		print_tree(sibling);
	}
}

